import { ChooseLanguagePage } from "./../choose-language/choose-language.page";
import { Component } from "@angular/core";
import { AdMobFree } from "@ionic-native/admob-free/ngx";
import { BarcodeScanner } from "@ionic-native/barcode-scanner/ngx";
import { Ndef, NdefRecord, NFC } from "@ionic-native/nfc/ngx";
import { AlertController, LoadingController, ModalController, ToastController } from "@ionic/angular";
import { Global } from "./../global.service";
import { LocalStorage } from "./../local-storage.service";
import { SettingsPage } from "./../settings/settings.page";
import { TagBookPage } from "./../tag-book/tag-book.page";

@Component({
	selector: "app-home",
	templateUrl: "home.page.html",
	styleUrls: ["home.page.scss"],
})
export class HomePage {
	readerMode: any;
	currentRewardInfo: any;

	constructor(
		private alertCtrl: AlertController,
		private loadingCtrl: LoadingController,
		private toastCtrl: ToastController,
		private modalCtrl: ModalController,
		private global: Global,
		private localStorage: LocalStorage,
		private adMobFree: AdMobFree,
		private nfc: NFC,
		private ndef: Ndef,
		private barcodeScanner: BarcodeScanner
	) {
		this.currentRewardInfo = {};
		this.adMobFree.on(this.adMobFree.events.REWARD_VIDEO_REWARD).subscribe(event => {
			this.currentRewardInfo = event;
			console.log(this.currentRewardInfo);
		});
		this.adMobFree.on(this.adMobFree.events.REWARD_VIDEO_CLOSE).subscribe(async () => {
			if (this.currentRewardInfo.rewardType) {
				switch (this.currentRewardInfo.rewardType) {
					case "scan":
						this.scan();
						break;
					case "read":
						this.read();
						break;
				}
			}
		});

		this.initLanguage();
	}

	initLanguage() {
		const language = this.localStorage.getData(Global.LANGUAGE);
		if (!language) {
			this.chooseLanguage();
		}
	}


	async chooseLanguage() {
		const modal = await this.modalCtrl.create({
			swipeToClose: true,
			presentingElement: await this.modalCtrl.getTop(),
			component: ChooseLanguagePage
		});

		await modal.present();
	}


	async scanNFC() {
		if (this.global.needShowAd && !this.global.isFree) {
			const alert = await this.alertCtrl.create({
				header: this.translate("GET_VIP"),
				message: this.translate("GET_VIP_MESSAGE"),
				buttons: [{
					text: this.translate("WATCH_AND_UNLOCK"),
					handler: () => {
						this.prepareVideoAd(Global.VIDEO_SCAN_ID);
					}
				}, {
					text: this.translate("CANCEL"),
					role: "cancel",
				}]
			});
			alert.present();
		} else {
			this.scan();
		}
	}

	async readNFC() {
		if (this.global.needShowAd && !this.global.isFree) {
			const alert = await this.alertCtrl.create({
				header: this.translate("GET_VIP"),
				message: this.translate("GET_VIP_MESSAGE"),
				buttons: [{
					text: this.translate("WATCH_AND_UNLOCK"),
					handler: () => {
						this.prepareVideoAd(Global.VIDEO_READ_ID);
					}
				}, {
					text: this.translate("CANCEL"),
					role: "cancel",
				}]
			});
			alert.present();
		} else {
			this.read();
		}
	}

	private async prepareVideoAd(id: string) {
		const loading = await this.loadingCtrl.create();
		await loading.present();
		this.currentRewardInfo = {};
		this.adMobFree.rewardVideo.config({
			id,
			isTesting: false,
			autoShow: true
		});
		this.adMobFree.rewardVideo.prepare().then().finally(() => {
			loading.dismiss();
		});
	}

	private async read() {
		this.nfc.scanNdef().then(tag => {
			console.log(tag);
			if (tag.ndefMessage) {
				for (const message of tag.ndefMessage) {
					this.saveTag(message);
				}
			}
		}, async (err) => {
			this.toast(err);
		});
	}

	private async scan() {
		this.barcodeScanner.scan().then(result => {
			try {
				console.log(JSON.parse(result.text));
				const tag: NdefRecord = JSON.parse(result.text);
				if (tag.id !== undefined && tag.payload !== undefined && tag.tnf !== undefined && tag.type !== undefined) {
					this.saveTag(JSON.parse(result.text));
					this.tags();
				} else {
					this.toast(this.translate("NOT_A_NFC_TAG"));
				}
			} catch (e) {
				this.toast(this.translate("NOT_A_NFC_TAG"));
			}
		});
	}

	private saveTag(tag: NdefRecord) {
		const tags = this.localStorage.getData(Global.TAGS);
		if (!tags) {
			this.localStorage.setData(Global.TAGS, [tag]);
		} else {
			tags.unshift(tag);
			this.localStorage.setData(Global.TAGS, tags);
		}
	}

	private async toast(message: string) {
		const toast = await this.toastCtrl.create({
			message,
			duration: 3000
		});
		await toast.present();
	}

	async tags() {
		const modal = await this.modalCtrl.create({
			swipeToClose: true,
			presentingElement: await this.modalCtrl.getTop(),
			component: TagBookPage
		});

		await modal.present();
	}


	async settings() {
		const modal = await this.modalCtrl.create({
			swipeToClose: true,
			presentingElement: await this.modalCtrl.getTop(),
			component: SettingsPage
		});

		await modal.present();
	}

	translate(key: string) {
		return this.global.translate(key);
	}

}
